In [ ]:
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from dataset import *
from plots import *
from metrics import *
from models_functions import *
# Set style for matplotlib
plt.style.use("Solarize_Light2")
import plotly.io as pio
pio.renderers.default = "notebook_connected"
WARNING:tensorflow:From c:\Users\VG User\Documents\GitHub\MLinAPP-FP01-14\.venv\Lib\site-packages\keras\src\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.
In [ ]:
# Path to the root directory of the dataset
ROOTDIR_DATASET_NORMAL = '../dataset/normal'
ROOTDIR_DATASET_ANOMALY = '../dataset/collisions'
# TF_ENABLE_ONEDNN_OPTS=0 means that the model will not use the oneDNN library for optimization
import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
Various parameters¶
In [ ]:
#freq = '1.0'
#freq = '0.1'
#freq = '0.01'
freq = '0.005'
file_name_normal = "_20220811_rbtc_"
file_name_collisions = "_collision_20220811_rbtc_"
recording_normal = [0, 2, 3, 4]
recording_collisions = [1, 5]
freq_str = freq.replace(".", "_")
features_folder_normal = f"./features/normal{freq_str}/"
features_folder_collisions = f"./features/collisions{freq_str}/"
Data¶
In [ ]:
df_features_normal, df_normal_raw, _ = get_dataframes(ROOTDIR_DATASET_NORMAL, file_name_normal, recording_normal, freq, None)
df_features_collisions, df_collisions_raw, df_collisions_raw_action = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, recording_collisions, freq, None)
df_features_collisions_1, df_collisions_raw_1, df_collisions_raw_action_1 = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, [1], freq, None)
df_features_collisions_5, df_collisions_raw_5, df_collisions_raw_action_5 = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, [5], freq, None)
Loading data. Found 31 different actions. Loading data done. Computing features.
Progress: 0% Complete
Skipped feature extraction for pickFromPallet(1,2)=[true,1,0] 2022-08-11 14:37:37.436000 : 2022-08-11 14:37:37.421000. Skipped feature extraction for placeToPallet(1,1)=[true,0] 2022-08-11 14:37:37.421000 : 2022-08-11 14:37:37.442000. Skipped feature extraction for pickFromPallet(3,2)=[true,1,0] 2022-08-11 15:36:32.568000 : 2022-08-11 15:36:32.533000. Skipped feature extraction for pickFromPallet(3,2)=[true,1,0] 2022-08-11 15:36:32.572000 : 2022-08-11 15:36:32.561000. Skipped feature extraction for placeToPallet(1,3)=[true,0] 2022-08-11 15:36:32.533000 : 2022-08-11 15:36:32.572000. Skipped feature extraction for placeToPallet(1,3)=[true,0] 2022-08-11 15:36:32.561000 : 2022-08-11 15:36:32.561000. --- 118.75116038322449 seconds --- Loading data. Found 31 different actions. Loading data done. Computing features.
Progress: 0% Complete
Skipped feature extraction for moveOverPallet(1,3)=[true,0] 2022-08-11 16:55:15.149000 : 2022-08-11 16:55:15.146000. Skipped feature extraction for moveOverPallet(3,1)=[true,0] 2022-08-11 16:55:15.146000 : 2022-08-11 16:55:15.150000. --- 43.83658695220947 seconds --- Loading data. Found 31 different actions. Loading data done. Computing features.
Progress: 0% Complete
--- 21.850510597229004 seconds --- Loading data. Found 31 different actions. Loading data done. Computing features.
Progress: 0% Complete
Skipped feature extraction for moveOverPallet(1,3)=[true,0] 2022-08-11 16:55:15.149000 : 2022-08-11 16:55:15.146000. Skipped feature extraction for moveOverPallet(3,1)=[true,0] 2022-08-11 16:55:15.146000 : 2022-08-11 16:55:15.150000. --- 25.490682125091553 seconds ---
In [ ]:
# df_features_normal, df_normal_raw, _ = get_dataframes(ROOTDIR_DATASET_NORMAL, file_name_normal, recording_normal, freq, f"{features_folder_normal}")
# df_features_collisions, df_collisions_raw, df_collisions_raw_action = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, recording_collisions, freq, f"{features_folder_collisions}1_5/")
# df_features_collisions_1, df_collisions_raw_1, df_collisions_raw_action_1 = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, [1], freq, f"{features_folder_collisions}1/")
# df_features_collisions_5, df_collisions_raw_5, df_collisions_raw_action_5 = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, [5], freq, f"{features_folder_collisions}5/")
In [ ]:
X_train, y_train, X_test, y_test, df_test = get_train_test_data(df_features_normal, df_features_collisions, full_normal=True)
X_train_1, y_train_1, X_test_1, y_test_1, df_test_1 = get_train_test_data(df_features_normal, df_features_collisions_1, full_normal=True)
X_train_5, y_train_5, X_test_5, y_test_5, df_test_5 = get_train_test_data(df_features_normal, df_features_collisions_5, full_normal=True)
Collisions¶
In [ ]:
collisions_rec1, collisions_init1 = get_collisions('1', ROOTDIR_DATASET_ANOMALY)
collisions_rec5, collisions_init5 = get_collisions('5', ROOTDIR_DATASET_ANOMALY)
# Merge the collisions of the two recordings in one dataframe
collisions_rec = pd.concat([collisions_rec1, collisions_rec5])
collisions_init = pd.concat([collisions_init1, collisions_init5])
In [ ]:
collisions_zones, y_collisions = get_collisions_zones_and_labels(collisions_rec, collisions_init, df_features_collisions)
collisions_zones_1, y_collisions_1 = get_collisions_zones_and_labels(collisions_rec1, collisions_init1, df_features_collisions_1)
collisions_zones_5, y_collisions_5 = get_collisions_zones_and_labels(collisions_rec5, collisions_init5, df_features_collisions_5)
LSTM-ED for Anomaly Detection in Time Series Data¶
In [ ]:
from algorithms.lstm_enc_dec_axl import LSTMED
classifier = LSTMED(
name='LSTM-ED',
num_epochs=50,
batch_size=64,
lr=1e-3,
hidden_size=64,
sequence_length=100,
train_gaussian_percentage=0.30,
n_layers=(2, 2),
use_bias=(True, True),
dropout=(0.1, 0.1),
seed=42,
gpu=None, # Set to None for CPU, or specify GPU index if available
details=True
)
# Train the LSTM on normal data
classifier.fit(X_train)
print("LSTM-ED training completed.")
100%|██████████| 50/50 [01:37<00:00, 1.94s/it]
LSTM-ED training completed.
Predictions¶
In [ ]:
df_test = get_statistics(X_test, y_collisions, classifier, df_test, freq, threshold_type="mad")
df_test_1 = get_statistics(X_test_1, y_collisions_1, classifier, df_test_1, freq, threshold_type="mad")
df_test_5 = get_statistics(X_test_5, y_collisions_5, classifier, df_test_5, freq, threshold_type="mad")
Anomaly prediction completed.
Number of anomalies detected: 1 with threshold 13084435615.576904, std
Number of anomalies detected: 118 with threshold 162.9702962940295, mad
Number of anomalies detected: 16 with threshold 779.0025365561331, percentile
Number of anomalies detected: 6 with threshold 1014.7057885453083, IQR
Number of anomalies detected: 306 with threshold 0.0, zero
choosen threshold type: mad, with value: 162.9703
F1 Score: 0.9417
Accuracy: 0.9575
Precision: 0.8898
Recall: 1.0000
precision recall f1-score support
0 1.00 0.94 0.97 201
1 0.89 1.00 0.94 105
accuracy 0.96 306
macro avg 0.94 0.97 0.95 306
weighted avg 0.96 0.96 0.96 306
ROC AUC Score: 0.9774
Anomalies detected: 118
Best threshold: 173.4108 | F1 Score: 0.9417 | Precision: 0.8898 | Recall: 1.0000
Anomalies detected with best threshold: 118
-------------------------------------------------------------------------------------
Anomaly prediction completed.
Number of anomalies detected: 1 with threshold 18030223610.182114, std
Number of anomalies detected: 45 with threshold 139.055142476544, mad
Number of anomalies detected: 9 with threshold 717.5305852775556, percentile
Number of anomalies detected: 31 with threshold 245.15972109615694, IQR
Number of anomalies detected: 164 with threshold 0.0, zero
choosen threshold type: mad, with value: 139.0551
F1 Score: 0.8750
Accuracy: 0.9390
Precision: 0.7778
Recall: 1.0000
precision recall f1-score support
0 1.00 0.92 0.96 129
1 0.78 1.00 0.88 35
accuracy 0.94 164
macro avg 0.89 0.96 0.92 164
weighted avg 0.95 0.94 0.94 164
ROC AUC Score: 0.9805
Anomalies detected: 45
Best threshold: 184.9405 | F1 Score: 0.9067 | Precision: 0.8500 | Recall: 0.9714
Anomalies detected with best threshold: 40
-------------------------------------------------------------------------------------
Anomaly prediction completed.
Number of anomalies detected: 2 with threshold 1018.983006434978, std
Number of anomalies detected: 25 with threshold 648.9818858885125, mad
Number of anomalies detected: 8 with threshold 844.7135347042098, percentile
Number of anomalies detected: 2 with threshold 1329.8081279069997, IQR
Number of anomalies detected: 141 with threshold 0.0, zero
choosen threshold type: mad, with value: 648.9819
F1 Score: 0.5432
Accuracy: 0.7376
Precision: 0.8800
Recall: 0.3929
precision recall f1-score support
0 0.71 0.96 0.82 85
1 0.88 0.39 0.54 56
accuracy 0.74 141
macro avg 0.79 0.68 0.68 141
weighted avg 0.78 0.74 0.71 141
ROC AUC Score: 0.9538
Anomalies detected: 25 Best threshold: 424.2105 | F1 Score: 0.9231 | Precision: 0.8852 | Recall: 0.9643 Anomalies detected with best threshold: 61 -------------------------------------------------------------------------------------
In [ ]:
plot_anomalies_true_and_predicted(df_collisions_raw, df_collisions_raw_action, collisions_zones, df_test, title="Collisions zones vs predicted zones for both recordings")